# 发邮箱
import hashlib
import os
import re
import smtplib
import threading
from email.mime.text import MIMEText
from email.utils import formataddr
import jwt
from mydjango import settings
import redis
import pymysql
import time
import hmac
import urllib.parse
import requests, json   #导入依赖库

redis1 = redis.Redis(host=settings.Django_HOST,port=6379, db=1,decode_responses=True)

redis = redis.Redis(host=settings.Django_HOST,port=6379, db=0)
import base64

import upyun

# 定义参数
my_mail = '347155713@qq.com'
# 邮箱授权码
my_pass = 'oowgpztkfebkbjed'

# 又拍云操作员账号,密码,空间名称
username = 'f347155713'
password = 'hgPbQPJkVSHg1myBYN65Q1ZkjI4uvIax'
upyun_name = 'work-image'


# 根据token获取用户id
def get_uid(request=None, token=None):
    if not token:
        # 根据token获取用户的uid
        token = request.META.get("HTTP_AUTHORIZATION")

    token = token[4:]

    uid = chack_jwt(token).get("uid")
    return uid

from celery.task import task
# 定义发送邮件方法
@task
def mail(subject, content, mailaddr):
    # time.sleep(10)
    # 声明邮件对象
    msg = MIMEText(content, 'plain', 'utf-8')

    # 设置发送方对象
    msg['From'] = formataddr(['在线教育平台', my_mail])

    # 设置收件方对象
    msg['To'] = formataddr(['尊敬的客户', mailaddr])

    # 设置标题
    msg['Subject'] = subject

    # 设置smtp服务器
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)

    # 登录邮箱
    server.login(my_mail, my_pass)

    # 发送邮件
    server.sendmail(my_mail, [mailaddr], msg.as_string())

    # 关闭smtp链接
    server.quit()


# 发送短信验证码
def send_phone_code(send_phone, num):
    # 短信应用SDK AppID
    appid = '1400373174'  # SDK AppID是1400开头

    # 短信应用SDK AppKey
    appkey = "7b8eebd19d6600c45333aba5ab62796d"

    # 需要发送短信的手机号码
    phone_numbers = [send_phone]

    # 短信模板ID，需要在短信应用中申请
    template_id = '614434'

    # 签名
    sms_sign = "刘悦的技术博客"

    from qcloudsms_py import SmsSingleSender
    from qcloudsms_py.httpclient import HTTPError

    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context

    ssender = SmsSingleSender(appid, appkey)
    params = [num, "2"]  # 当模板没有参数时，`params = []`
    try:
        result = ssender.send_with_param(86, phone_numbers[0],
                                         template_id, params, sign=sms_sign, extend="", ext="")  # 签名参数不允许为空串
        return result
    except HTTPError as e:
        return e
    except Exception as e:
        return e


# jwt对用户信息加密
def make_jwt(userinfo):
    # 加密
    encode_jwt = jwt.encode(userinfo, settings.SECRET_KEY, algorithm='HS256')

    return encode_jwt.decode()

# jwt解密
def chack_jwt(code):
    # 解密
    decode_jwt = jwt.decode(
        code,
        settings.SECRET_KEY,
        algorithms=['HS256'])

    return decode_jwt


# 重写make_password方法使用md5进行加密
def make_password(mypass):
    md5 = hashlib.md5()

    # 定义加密对象
    sign_str = mypass
    # 转码
    sign_utf8 = str(sign_str).encode(encoding='utf-8')
    # 加密
    md5.update(sign_utf8)
    # 生成密文
    md5_server = md5.hexdigest()

    return md5_server


# 数据库查询
class MysqlFind:

    def __init__(self, sql):
        self.db = pymysql.connect(host=settings.Django_HOST, port=3306, database='workflow', user='root', password="mysql", charset="utf8")
        self.cursor = self.db.cursor()
        self.sql = sql

    def sql_select(self):

        self.cursor.execute(self.sql)
        desc = self.cursor.description
        result = [dict(zip([col[0] for col in desc], row)) for row in self.cursor.fetchall()]
        return result

    def sql_update(self):
        self.cursor.execute(self.sql)
        self.db.commit()
        return True

    def __del__(self):
        self.cursor.close()
        self.db.close()


def base64encode(f):
    data = f.read()
    encodestr = base64.b64encode(data)
    return encodestr.decode()


# 上传又拍云
def uploadFile(name, chunk):
    up = upyun.UpYun('work-image', username='f347155713', password='hgPbQPJkVSHg1myBYN65Q1ZkjI4uvIax')
    headers = {
        "x-gmkerl-rotate": "auto"
    }
    res = up.put(name, chunk, checksum=True, headers=headers)

    return res

    # uploader = up.init_multi_uploader("/upyun-python-sdk/upyun_nothread.txt")
    #
    # # 采用多线程调用上传
    # threads = []
    #
    # t1 = threading.Thread(target=uploader.upload, args=(0, os.urandom(1024 * 1024)))
    #
    # threads.append(t1)
    #
    # t2 = threading.Thread(target=uploader.upload, args=(1, os.urandom(1024 * 1024)))
    #
    # threads.append(t2)
    #
    # # 启动多线程
    # for t in threads:
    #     t.start()
    #     # 阻塞主线程
    #     # t.join()
    #
    # # 声明调用结束
    # res = uploader.complete()


# 钉钉机器人
class DingInform:
    def __init__(self):
        self.timestamp = str(round(time.time() * 1000))
        self.secret = 'SEC1c2c8b49cc479c0545821db20896a883d5e99e2f48ad9e4e5122794ee3dc83cc'
        self.secret_enc = self.secret.encode('utf-8')
        self.string_to_sign = '{}\n{}'.format(self.timestamp, self.secret)
        self.string_to_sign_enc = self.string_to_sign.encode('utf-8')
        self.hmac_code = hmac.new(self.secret_enc, self.string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote(base64.b64encode(self.hmac_code))

        # url = os.path.join(os.path.join(BASE_DIR,'static/upload'), '', 'wallhaven-39xv99.jpg')
    def send_ding(self, content, phone):
        headers={'Content-Type': 'application/json'}   #定义数据类型
        # https://oapi.dingtalk.com/robot/send?access_token=223bc07b2d8fad1333d4952b9277b91775ad1f66fb558898d68135d45bf9317f
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=f5f0d4c81205a8281705151fe3520df81ae5c8725587da0350ebb1feb13c7a6a&timestamp='+self.timestamp+"&sign="+self.sign
        #定义要发送的数据
        #"at": {"atMobiles": "['"+ mobile + "']"
        # os.path.join(UPLOAD_ROOT, '', 'wallhaven-39xv99.jpg'
        data = {
             "msgtype": "markdown",  # 使用markdown形式推送
             "markdown": {
                 "title":"审批结果",
                 "text": content
             },
              "at": {
                  "atMobiles": [   # 要艾特的人，填写在钉钉中的手机号即可
                      # phone
                      '17686498310'
                  ],
                  "isAtAll": False  # 是否艾特所以人
              }
         }
        res = requests.post(webhook, data=json.dumps(data), headers=headers)   #发送post请求

        print(res.text)









